import React from 'react';
import { connect } from 'dva';
import router from 'umi/router';

import request from '../utils/request';
import { getPSITokenId, removePSITokenId } from '../utils/tokenId';

import { withStyles } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';

import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';

import BottomNavigation from '@material-ui/core/BottomNavigation';
import BottomNavigationAction from '@material-ui/core/BottomNavigationAction';

import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction';
import IconButton from '@material-ui/core/IconButton';

import RightArrowIcon from '@material-ui/icons/KeyboardArrowRight'

import HomeIcon from '@material-ui/icons/Home';
import AboutIcon from '@material-ui/icons/Whatshot'

import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';
import Button from '@material-ui/core/Button';

import { MuiThemeProvider } from '@material-ui/core/styles';
import CssBaseline from '@material-ui/core/CssBaseline';
import Grid from '@material-ui/core/Grid';
import LinearProgress from '@material-ui/core/LinearProgress';

import mainTheme from '../theme/mainTheme';
import MsgConfirm from '../utils/msgconfirm';

import About from '../components/About';

const styles = theme => ({
  root: {
    height: '100%'
  },
  content: {
    flexGrow: 1,
    overflow: 'auto',
    width: '100%',
    padding: 20,
  },
  menuButton: {
    marginLeft: -12,
    marginRight: 20,
  },
});

class IndexPage extends React.Component {

  constructor(props) {
    super(props);

    if (!getPSITokenId()) {
      router.replace('/auth/login');
    }

    this.state = {
      bottomNav: 'mainMenu',
      msgBoxOpen: false,
      msgBoxInfo: '',
      confirmBoxOpen: false,
      confirmBoxInfo: '',
      mainMenuItems: [],
      selectedTabIndex: 0,
      loding: false,
    }
  }

  componentDidMount = () => {
    // 主菜单
    let formData = new FormData();
    formData.append("tokenId", getPSITokenId());

    this.setState({
      loading: true
    });

    request('/web/API/MainMenu/mainMenuItems', {
      credentials: 'include',
      method: "POST",
      body: formData,
    }).then(({ data }) => {
      this.setState({ mainMenuItems: data, loading: false });
    });
  }

  render() {
    const { classes } = this.props;
    const { bottomNav, loading } = this.state;
    document.title ='PSI';
    return (
      <MuiThemeProvider theme={mainTheme}>
        <CssBaseline />
        <Grid container direction='column' wrap='nowrap' className={classes.root}>
          <Grid item>
            <AppBar position='static'>
              <Toolbar>
                <IconButton className={classes.menuButton}
                  onClick={() => { this.setState({ bottomNav: 'about' }) }}>
                  <AboutIcon color='inherit' />
                </IconButton>
                <Typography variant="title" color="inherit">
                  PSI
              </Typography>
              </Toolbar>
            </AppBar>
          </Grid>
          <LinearProgress color='secondary' hidden={!loading} />

          <Grid item className={classes.content}>
            <div hidden={bottomNav !== 'mainMenu'}>
              {
                this.state.mainMenuItems.map((it, index) => {
                  return <List key={index} subheader={it.caption} component="nav">
                    {
                      it.items.map((item2, index2) => {
                        return <ListItem key={index2} button divider
                          onClick={() => { this.naviagetTo(item2.fid) }}>
                          <ListItemText primary={item2.caption}>{}</ListItemText>
                          <ListItemSecondaryAction>
                            <IconButton onClick={() => this.naviagetTo(item2.fid)}>
                              <RightArrowIcon />
                            </IconButton>
                          </ListItemSecondaryAction>
                        </ListItem>
                      })
                    }
                  </List>
                })
              }
            </div>
            <div hidden={bottomNav !== 'about'} style={{ width: '100%', overflow: 'hidden' }}>
              <Grid container direction='column' wrap='nowrap' spacing={40}>
                <Grid item>
                  <About />
                </Grid>

                <Grid item>
                  <Grid container justify='center'>
                    <Button variant="raised" color="primary" fullWidth onClick={this.logoutConfirm} >
                      安全退出
                    </Button>
                  </Grid>
                </Grid>
              </Grid>
            </div>
          </Grid>

          <Grid item>
            <BottomNavigation
              value={bottomNav}
              showLabels
              onChange={this.onNavChange}
            >
              <BottomNavigationAction value={'mainMenu'} label="主菜单" icon={<HomeIcon />} />
              <BottomNavigationAction value={'about'} label="关于" icon={<AboutIcon />} />
            </BottomNavigation>
          </Grid>

          <Dialog open={this.state.msgBoxOpen}>
            <DialogTitle>PSI</DialogTitle>
            <DialogContent>
              <DialogContentText>
                {this.state.msgBoxInfo}
              </DialogContentText>
            </DialogContent>
            <DialogActions>
              <Button onClick={() => { this.setState({ msgBoxOpen: false }) }} color="primary" autoFocus>
                确定
          </Button>
            </DialogActions>
          </Dialog>
          <MsgConfirm open={this.state.confirmBoxOpen}
            info={this.state.confirmBoxInfo}
            onCancel={() => { this.setState({ confirmBoxOpen: false }) }}
            onOK={() => { this.setState({ confirmBoxOpen: false }); this.doLogout(); }} >
          </MsgConfirm>
        </Grid >
      </MuiThemeProvider>
    );
  }

  onNavChange = (event, value) => {
    this.setState({ bottomNav: value });
  }

  logoutConfirm = () => {
    this.setState({
      confirmBoxOpen: true,
      confirmBoxInfo: '请确认是否退出?'
    });
  }

  doLogout = () => {
    var formData = new FormData();
    formData.append("tokenId", getPSITokenId());

    request('/web/API/User/doLogout', {
      credentials: 'include',
      method: "POST",
      body: formData,
    }).then(({ data }) => {
      if (data.success) {
        removePSITokenId();
        router.replace('/auth/login');
      } else {
        this.setState({
          msgBoxInfo: data.msg,
          msgBoxOpen: true
        });
      }
    });
  }

  naviagetTo = (fid) => {
    var formData = new FormData();
    formData.append("tokenId", getPSITokenId());
    formData.append('fid', fid);

    // 记录业务日志
    request('/web/API/Bizlog/enterModule', {
      credentials: 'include',
      method: "POST",
      body: formData,
    });

    switch (fid) {
      // 客户资料
      case '1007':
        router.push('/customer');
        break;
      case '2028':
        router.push('/sobill');
        break;
      default:
        this.todo();
    }
  }

  todo = () => {
    this.setState({
      msgBoxInfo: '本模块还在开发中',
      msgBoxOpen: true
    });
  }
}

IndexPage.propTypes = {
};

export default connect()(withStyles(styles)(IndexPage));
